package com.graduation.check.service.impl;

import com.graduation.check.dto.TeacherStatisticsResponse;
import com.graduation.check.mapper.TeacherStatisticsMapper;
import com.graduation.check.service.TeacherStatisticsService;
import com.graduation.check.utils.TypeConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TeacherStatisticsServiceImpl implements TeacherStatisticsService {
    
    @Autowired
    private TeacherStatisticsMapper teacherStatisticsMapper;
    
    @Override
    public TeacherStatisticsResponse getOverviewStatistics(
            LocalDateTime startDate, 
            LocalDateTime endDate, 
            String major, 
            String className) {
        
        log.info("开始获取综合统计数据 - startDate: {}, endDate: {}, major: {}, className: {}", 
                startDate, endDate, major, className);
        
        TeacherStatisticsResponse response = new TeacherStatisticsResponse();
        
        try {
            // 1. 基础统计
            log.debug("开始查询基础统计数据");
            Map<String, Object> basicData = teacherStatisticsMapper.getBasicStatistics(startDate, endDate, major, className);
        TeacherStatisticsResponse.BasicStats basicStats = new TeacherStatisticsResponse.BasicStats();
        basicStats.setTotalStudents(TypeConverter.getIntValue(basicData, "totalStudents"));
        basicStats.setActiveStudents(TypeConverter.getIntValue(basicData, "activeStudents"));
        basicStats.setTotalSubmissions(TypeConverter.getIntValue(basicData, "totalSubmissions"));
        basicStats.setCompletedSubmissions(TypeConverter.getIntValue(basicData, "completedSubmissions"));
        basicStats.setAvgSubmissionsPerStudent(TypeConverter.getDoubleValue(basicData, "avgSubmissionsPerStudent"));
        basicStats.setAvgSimilarity(TypeConverter.getDoubleValue(basicData, "avgSimilarity"));
        basicStats.setAvgProcessingTime(TypeConverter.getIntValue(basicData, "avgProcessingTime"));
        response.setBasicStats(basicStats);
        
        // 2. 风险分析
        Map<String, Object> riskData = teacherStatisticsMapper.getRiskAnalysis(startDate, endDate);
        TeacherStatisticsResponse.RiskAnalysis riskAnalysis = new TeacherStatisticsResponse.RiskAnalysis();
        
        TeacherStatisticsResponse.RiskLevel highRisk = new TeacherStatisticsResponse.RiskLevel();
        highRisk.setCount(TypeConverter.getIntValue(riskData, "highRiskCount"));
        highRisk.setPercentage(TypeConverter.getDoubleValue(riskData, "highRiskPercentage"));
        highRisk.setThreshold("> 30%");
        
        TeacherStatisticsResponse.RiskLevel mediumRisk = new TeacherStatisticsResponse.RiskLevel();
        mediumRisk.setCount(TypeConverter.getIntValue(riskData, "mediumRiskCount"));
        mediumRisk.setPercentage(TypeConverter.getDoubleValue(riskData, "mediumRiskPercentage"));
        mediumRisk.setThreshold("15% - 30%");
        
        TeacherStatisticsResponse.RiskLevel lowRisk = new TeacherStatisticsResponse.RiskLevel();
        lowRisk.setCount(TypeConverter.getIntValue(riskData, "lowRiskCount"));
        lowRisk.setPercentage(TypeConverter.getDoubleValue(riskData, "lowRiskPercentage"));
        lowRisk.setThreshold("< 15%");
        
        riskAnalysis.setHighRisk(highRisk);
        riskAnalysis.setMediumRisk(mediumRisk);
        riskAnalysis.setLowRisk(lowRisk);
        response.setRiskAnalysis(riskAnalysis);
        
        // 3. 专业分布
        List<Map<String, Object>> majorData = teacherStatisticsMapper.getMajorDistribution(startDate, endDate);
        List<TeacherStatisticsResponse.MajorDistribution> majorDistribution = majorData.stream()
            .map(m -> {
                TeacherStatisticsResponse.MajorDistribution dist = new TeacherStatisticsResponse.MajorDistribution();
                dist.setMajor((String) m.get("major"));
                dist.setStudentCount(TypeConverter.getIntValue(m, "studentCount"));
                dist.setSubmissionCount(TypeConverter.getIntValue(m, "submissionCount"));
                dist.setAvgSimilarity(TypeConverter.getDoubleValue(m, "avgSimilarity"));
                return dist;
            })
            .collect(Collectors.toList());
        response.setMajorDistribution(majorDistribution);
        
        // 4. 班级分布
        List<Map<String, Object>> classData = teacherStatisticsMapper.getClassDistribution(startDate, endDate, major);
        List<TeacherStatisticsResponse.ClassDistribution> classDistribution = classData.stream()
            .map(c -> {
                TeacherStatisticsResponse.ClassDistribution dist = new TeacherStatisticsResponse.ClassDistribution();
                dist.setClassName((String) c.get("className"));
                dist.setStudentCount(TypeConverter.getIntValue(c, "studentCount"));
                dist.setSubmissionCount(TypeConverter.getIntValue(c, "submissionCount"));
                dist.setAvgSimilarity(TypeConverter.getDoubleValue(c, "avgSimilarity"));
                dist.setCompletionRate(TypeConverter.getDoubleValue(c, "completionRate"));
                return dist;
            })
            .collect(Collectors.toList());
        response.setClassDistribution(classDistribution);
        log.info("班级分布数据获取成功，共 {} 条记录", classDistribution.size());
        
        // 5. 最近活动（修复类型转换问题）
        Map<String, Object> activityData = teacherStatisticsMapper.getRecentActivity();
        TeacherStatisticsResponse.RecentActivity recentActivity = new TeacherStatisticsResponse.RecentActivity();
        recentActivity.setTodaySubmissions(TypeConverter.getIntValue(activityData, "todaySubmissions"));
        recentActivity.setYesterdaySubmissions(TypeConverter.getIntValue(activityData, "yesterdaySubmissions"));
        recentActivity.setWeekSubmissions(TypeConverter.getIntValue(activityData, "weekSubmissions"));
        recentActivity.setMonthSubmissions(TypeConverter.getIntValue(activityData, "monthSubmissions"));
        response.setRecentActivity(recentActivity);
        
        log.info("综合统计数据获取成功");
        return response;
        } catch (Exception e) {
            log.error("获取综合统计数据失败", e);
            throw new RuntimeException("获取统计数据失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public Map<String, Object> getTrendStatistics(String period, Integer days, String groupBy) {
        List<Map<String, Object>> trends = teacherStatisticsMapper.getSubmissionTrends(days, period);
        
        Map<String, Object> result = new HashMap<>();
        result.put("submissionTrends", trends);
        result.put("similarityTrends", trends);
        
        return result;
    }
    
    @Override
    public Map<String, Object> getStudentActivity() {
        return teacherStatisticsMapper.getStudentActivity();
    }
}
